package com.web.exiaodao.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.excelUtil.ExcelColumn;
import com.web.webstart.base.excelUtil.ExcelHead;
import com.web.webstart.base.excelUtil.ExcelHelper;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.exiaodao.business.entity.ExperienceTicketRecord;
import com.web.exiaodao.business.repository.ExperienceTicketRecordRepository;
import com.web.exiaodao.business.service.ExperienceTicketRecordService;
import com.web.exiaodao.remote.vo.ExperienceTicketRecordVo;

@Service("ExperienceTicketRecordService")
@Transactional(readOnly = false)
public class ExperienceTicketRecordServiceImpl extends BaseService<ExperienceTicketRecord> implements ExperienceTicketRecordService {

	private static final Logger LOGGER = Logger.getLogger(ExperienceTicketRecordServiceImpl.class);

	@Autowired
	private ExperienceTicketRecordRepository experienceTicketRecordRepository;

	/**
	 * 查询单条ExperienceTicketRecord信息
	 * //@param tId
	 * @return 返回单个ExperienceTicketRecord对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<ExperienceTicketRecord> findOne(Long modelId) throws BusinessException {
		ExperienceTicketRecord obj = new ExperienceTicketRecord();
		if(modelId != 0){
			obj = experienceTicketRecordRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<ExperienceTicketRecord> xr = new XaResult<ExperienceTicketRecord>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(obj);
			LOGGER.info("后台----->查询单个实体----->ExperienceTicketRecord");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的ExperienceTicketRecord数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象ExperienceTicketRecord集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<ExperienceTicketRecord>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<ExperienceTicketRecord> page = experienceTicketRecordRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), ExperienceTicketRecord.class), pageable);
		XaResult<Page<ExperienceTicketRecord>> xr = new XaResult<Page<ExperienceTicketRecord>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态不等于）----->ExperienceTicketRecord");
		return xr;
	}

	/**
	 * 分页查询状态status的ExperienceTicketRecord数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象ExperienceTicketRecord集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<ExperienceTicketRecord>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<ExperienceTicketRecord> page = experienceTicketRecordRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), ExperienceTicketRecord.class), pageable);
		XaResult<Page<ExperienceTicketRecord>> xr = new XaResult<Page<ExperienceTicketRecord>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态等于）----->ExperienceTicketRecord");
		return xr;
	}

	/**
	 * 保存ExperienceTicketRecord信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<ExperienceTicketRecord> saveOrUpdate(ExperienceTicketRecord model) throws BusinessException {
		ExperienceTicketRecord obj = null;
		if(XaUtil.isNotEmpty(model.getId())){
			obj = experienceTicketRecordRepository.findOne(model.getId());
		}else{
			obj = new ExperienceTicketRecord();
		}
		obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
		obj.setExperienceTicketId(XaUtil.isNotEmpty(model.getExperienceTicketId()) ? model.getExperienceTicketId() : obj.getExperienceTicketId());
		obj = experienceTicketRecordRepository.save(obj);
		XaResult<ExperienceTicketRecord> xr = new XaResult<ExperienceTicketRecord>();
		xr.setObject(obj);
		LOGGER.info("后台新增或编辑数据成功！");
		return xr;
	}

	/**
	 * 修改ExperienceTicketRecord状态，可一次修改多条   3删除  -1锁定  1正常
	 * //@param userId
	 * @param modelIds
	 * @param status
	 * @return 返回ExperienceTicketRecord对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<ExperienceTicketRecord> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<ExperienceTicketRecord> xr = new XaResult<ExperienceTicketRecord>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				ExperienceTicketRecord obj = experienceTicketRecordRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = experienceTicketRecordRepository.save(obj);
				}
			}
		}
		LOGGER.info("批量修改数据状态成功！");
		return xr;
	}

	//领取体验券记录
	@Override
	public XaResult<Page<ExperienceTicketRecordVo>> findListNEStatus(
			Integer status, Map<String, Object> filterParams, Pageable pageable)
					throws BusinessException {
		StringBuffer sql=new StringBuffer("SELECT er.`id`,u.`user_name`,et.`name`,er.`create_time` ");
		sql.append("FROM `tb_xa_experienceticketrecord` er LEFT JOIN `tb_xa_user` u ON er.`user_id`=u.`id` LEFT JOIN `tb_xa_experienceticket` et ON er.`experience_ticket_id`=et.`id` ");
		sql.append("WHERE er.`status`<>").append(XaConstant.Status.delete);
//		sql.append(" AND et.`status`=").append(XaConstant.Status.publish);
		sql.append(" AND u.`status`<>").append(XaConstant.Status.delete);
		//统计数据库中数据个数
		StringBuffer sql1=new StringBuffer("select count(*) ");
		sql1.append("FROM `tb_xa_experienceticketrecord` er LEFT JOIN `tb_xa_user` u ON er.`user_id`=u.`id` LEFT JOIN `tb_xa_experienceticket` et ON er.`experience_ticket_id`=et.`id` ");
		sql1.append("WHERE er.`status`<>").append(XaConstant.Status.delete);
//		sql1.append(" AND et.`status`=").append(XaConstant.Status.publish);
		sql1.append(" AND u.`status`<>").append(XaConstant.Status.delete);
		//查询条件
		if(XaUtil.isNotEmpty(filterParams.get("LIKE_userName"))){
			sql.append(" AND u.`user_name` ").append(" like '%").append(filterParams.get("LIKE_userName")).append("%' ");
			sql1.append(" AND u.`user_name` ").append(" like '%").append(filterParams.get("LIKE_userName")).append("%' ");
		}
		if(XaUtil.isNotEmpty(filterParams.get("LIKE_name"))){
			sql.append(" AND et.`name` ").append(" like '%").append(filterParams.get("LIKE_name")).append("%' ");
			sql1.append(" AND et.`name` ").append(" like '%").append(filterParams.get("LIKE_name")).append("%' ");
		}
		sql.append(" ORDER BY er.`create_time` DESC");
		sql1.append(" ORDER BY er.`create_time` DESC");
		List<Object[]> objs=this.query(sql.toString(), pageable.getPageNumber()*pageable.getPageSize(), pageable.getPageSize());
		List<ExperienceTicketRecordVo> vos=new ArrayList<ExperienceTicketRecordVo>();

		for (Object[] obj : objs) {	
			ExperienceTicketRecordVo vo = new ExperienceTicketRecordVo();
			vo.setId(Long.valueOf(obj[0].toString()));
			vo.setUserName(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
			vo.setName(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
			vo.setCreateTime(XaUtil.isEmpty(obj[3])?"":obj[3].toString());
			vos.add(vo);
		}
		//执行查询语句
		List<Object[]> obj1=this.query(sql1.toString(), null, null);
		//将得到的查询结果强转成int类型
		int count=Integer.parseInt(obj1.get(0)+"");				
		//调用分页
		Page<ExperienceTicketRecordVo> page= new MyPage<ExperienceTicketRecordVo>(pageable.getPageNumber(),pageable.getPageSize(),vos,count);
		//创建结果集对象xr
		XaResult<Page<ExperienceTicketRecordVo>> xr=new XaResult<Page<ExperienceTicketRecordVo>>();
		//将page放入xr
		xr.setObject(page);
		return xr;
	}

	//导出excel
	@Override
	public void exportdata(Map<String, Object> filterParams,
			HttpServletResponse response, String modelIds)
			throws BusinessException {
		String sql = "SELECT er.`id`,u.`user_name`,et.`name`,er.`create_time` FROM `tb_xa_experienceticketrecord` er LEFT JOIN `tb_xa_user` u ON er.`user_id`=u.`id` LEFT JOIN `tb_xa_experienceticket` et ON er.`experience_ticket_id`=et.`id`WHERE er.`status`<>3 AND u.`status`<>3  AND er.id IN ("+modelIds+") ORDER BY er.`create_time` DESC";
		List<Object[]> objs = this.query(sql, null, null);
		List<ExperienceTicketRecordVo> experienceTicketList = new ArrayList<>();
        for (Object[] obj : objs) {	
			ExperienceTicketRecordVo vo = new ExperienceTicketRecordVo();
			vo.setId(Long.valueOf(obj[0].toString()));
			vo.setUserName(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
			vo.setName(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
			vo.setCreateTime(XaUtil.isEmpty(obj[3])?"":obj[3].toString());
			experienceTicketList.add(vo);
		}

        //excel结构
        List<ExcelColumn> excelColumns = new ArrayList<ExcelColumn>();
        excelColumns.add(new ExcelColumn(0, "id", "编号", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(1, "userName", "用户", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(2, "name", "体验券", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(3, "createTime", "领取时间", Cell.CELL_TYPE_STRING));

        //设置头部
        ExcelHead head = new ExcelHead();
        head.setRowCount(1); // 模板中头部所占行数
        head.setColumns(excelColumns);  // 列的定义
        //执行导出,第一个null是response参数，用来输出到浏览器，第二个null是要导出的数据集合
        ExcelHelper.getInstanse().exportExcelFile(response, head, experienceTicketList);

	}

}
